<template>
  <el-dialog
    :title="showTitle"
    :visible="showAddDialog"
    width="50%"
    @close="btnConcel"
  >
    <el-form
      ref="addFormRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
    >
      <el-form-item label="部门名称" prop="name">
        <el-input
          v-model="formData.name"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门编码" prop="code">
        <el-input
          v-model="formData.code"
          style="width: 80%"
          placeholder="1-50个字符"
        />
      </el-form-item>
      <el-form-item label="部门负责人" prop="manager">
        <el-select
          v-model="formData.manager"
          style="width: 80%"
          placeholder="请选择"
          @focus="getEmployees"
        >
          <el-option
            v-for="item in peoples"
            :key="item.id"
            :label="item.username"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="部门介绍" prop="introduce">
        <el-input
          v-model="formData.introduce"
          style="width: 80%"
          placeholder="1-300个字符"
          type="textarea"
          :rows="3"
        />
      </el-form-item>
    </el-form>
    <el-row slot="footer" type="flex" justify="center">
      <el-col :span="6">
        <el-button type="primary" size="small" @click="addOk">确 定</el-button>
        <el-button size="small" @click="btnConcel">取 消</el-button>
      </el-col>
    </el-row>
  </el-dialog>
</template>

<script>
import { getDepartments, addDepartments, getDepartmentDetail, updateDepartments } from '@/api/departments'
import { getEmployees } from '@/api/employees'
export default {
  name: 'AddDepts',
  components: {},
  props: {
    showAddDialog: {
      type: Boolean,
      required: true
    },
    treeNode: {
      type: Object,
      default: null
    }
  },
  data() {
    const checkNameRepeat = async(rule, value, callback) => {
      const { depts } = await getDepartments()
      // 这里存在一个 BUG: 当点击标题上面的添加子部门时,部门名称可以重复,因为这里比较的 id 没有传,直接被解析为了 undefined
      // undefined !== '' 所以就造成了这个 BUG
      // 解决方案1. 修改条件
      // const brotherDepts = depts.filter(item => item.pid === (this.treeNode.id === undefined ? '' : this.treeNode.id))
      // 解决方案2. 修改父组件的数据结构
      let brotherDepts
      if (this.formData.id) {
        // 编辑(检索所有的兄弟节点,并除外自己)
        brotherDepts = depts.filter(item => item.pid === this.treeNode.pid && item.id !== this.treeNode.id)
      } else {
        // 新增
        brotherDepts = depts.filter(item => item.pid === this.treeNode.id)
      }
      const f = brotherDepts.find(t => t.name === value)
      if (f) {
        callback(new Error('部门名称重复'))
      } else {
        callback()
      }
    }

    const checkCodeRepeat = async(rule, value, callback) => {
      const { depts } = await getDepartments()
      let f
      if (this.formData.id) {
        // 编辑
        f = depts.find(t => t.code === value && t.id !== this.treeNode.id)
      } else {
        // 新增
        f = depts.find(t => t.code === value)
      }
      if (f) {
        callback(new Error('部门编码重复'))
      } else {
        callback()
      }
    }
    return {
      formData: {
        name: '', // 部门名称
        code: '', // 部门编码
        manager: '', // 部门管理者
        introduce: '' // 部门介绍
      },
      // 校验规则
      formRules: {
        name: [{ required: true, message: '部门名称不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门名称要求1-50个字符', trigger: 'blur' },
          { validator: checkNameRepeat, trigger: 'blur' }],
        code: [{ required: true, message: '部门编码不能为空', trigger: 'blur' },
          { min: 1, max: 50, message: '部门编码要求1-50个字符', trigger: 'blur' },
          { validator: checkCodeRepeat, trigger: 'blur' }],
        manager: [{ required: true, message: '部门负责人不能为空', trigger: 'blur' }],
        introduce: [{ required: true, message: '部门介绍不能为空', trigger: 'blur' },
          { trigger: 'blur', min: 1, max: 300, message: '部门介绍要求1-50个字符' }]
      },
      peoples: []
    }
  },
  computed: {
    showTitle() {
      return this.formData.id ? '编辑部门' : '新增部门'
    }
  },
  watch: {},
  created() {},
  mounted() {},
  methods: {
    async getEmployees() {
      this.peoples = await getEmployees()
    },
    addOk() {
      this.$refs.addFormRef.validate(async isOk => {
        if (isOk) {
          if (this.formData.id) {
            // 编辑操作
            await updateDepartments(this.formData)
          } else {
            // 新增操作
            // 手动检查通过后,添加 pid 来自 父组件的 id
            await addDepartments({ ...this.formData, pid: this.treeNode.id })
          }
          this.$emit('addDepts')
          this.$emit('update:showAddDialog', false)
        }
      })
    },
    btnConcel() {
      // 方式1.通过el-form-item的prop来重置
      /**
      <el-form-item prop="id" style="display:none" />
      formData: {
        id: undefined,
      }
      */
      // 方式2,手动设置
      // this.formData = {
      //   name: '', // 部门名称
      //   code: '', // 部门编码
      //   manager: '', // 部门管理者
      //   introduce: '' // 部门介绍
      // }
      // 方式3. 通过 $options 获取其原型链上的 data 得到formData
      this.formData = this.$options.data().formData
      this.$emit('update:showAddDialog', false)
      this.$refs.addFormRef.resetFields()
    },
    async getDepartmentDetail(id) {
      this.formData = await getDepartmentDetail(id)
    }
  }
}
</script>

<style lang="less" scoped>
</style>
